package com.sync.utils.project.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sync.utils.common.enums.URLEnum;
import com.sync.utils.common.base.service.impl.BaseServiceImpl;
import com.sync.utils.common.utils.StringUtil;
import com.sync.utils.project.demo.pojo.*;
import com.sync.utils.project.demo.mapper.UserMapper;
import com.sync.utils.project.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDto> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDto getUserInfo(String account){
        LambdaQueryWrapper<UserDto> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDto::getAccount,account);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Integer getByAccountCounts(String account) {
        return userMapper.getByAccountCounts(account);
    }

    @CacheEvict(cacheNames = "user",key = "'getByAccount'",allEntries = false)
    @Override
    public UserInfo getByAccount(String account) {
        return userMapper.getByAccount(account);
    }

    //@Cacheable(cacheNames = "user",key = "'getUserList'")
    @Override
    public PageView<UserDto> getUserList(UserReq userReq) {
        Page<UserDto> pageVo = new Page<>(userReq.getPageNum(),userReq.getPageSize(),true);
        LambdaQueryWrapper<UserDto> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtil.isNotEmpty(userReq.getAccount()),UserDto::getAccount,userReq.getAccount())
                .eq(StringUtil.isNotEmpty(userReq.getStatus()),UserDto::getStatus,userReq.getStatus())
                .like(StringUtil.isNotEmpty(userReq.getUserName()),UserDto::getUsername,userReq.getUserName());
        IPage<UserDto> page = userMapper.selectPage(pageVo, queryWrapper);
        IPage<UserRes> pageData = page.convert(s -> {
            UserRes userRes = new UserRes();
            BeanUtils.copyProperties(s, userRes);
            return userRes;
        });
        return new PageView(pageData);
    }

    @Override
    public UserRes getUser(@Param("userId") String userId) {
        UserDto userDto = userMapper.selectById(userId);
        UserRes userRes = new UserRes();
        BeanUtil.copyProperties(userDto,userRes);
        return userRes;
    }

    @Override
    public int updateUserById(UserVo userVo) {
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(userVo,userDto);
        return userMapper.updateById(userDto);
    }

    @Override
    public int deleteUser(List<String> collectIds) {
        return userMapper.deleteBatchIds(collectIds);
    }

    @Override
    public int saveUser(UserVo userVo) {
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(userVo,userDto);
        return userMapper.insert(userDto);
    }

    @Cacheable(value = "user",key = "'getCityWeather'")
    @Override
    public JHApiResult getCityWeather(String city) {
        JHApiResult jhApiResult = null;
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("city",city);
            map.put("key",URLEnum.WEATHER_URL.getKey());
            String result = httpAPIService.doGet(URLEnum.WEATHER_URL.getUrl(), map);
            log.info("结果集："+result);

            //不为kong则，转成对象返回
            if (StringUtil.isNotEmpty(result)) {
                //转成对象
                jhApiResult = JSON.parseObject(result,JHApiResult.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jhApiResult;
    }

    @Override
    public JHApiResult getNews(HttpServletRequest request,Integer page,Integer pageSize) {
        String type = "top";
        JHApiResult jhApiResult = null;
        Map<String,Object> map = new HashMap<>();
        map.put("key",URLEnum.NEWS_URL.getKey());
        map.put("type",type);
        map.put("page",page==null?1:page);
        map.put("page_size",pageSize==null?5:pageSize);
        try {
            String result = httpAPIService.doGet(URLEnum.NEWS_URL.getUrl(),map);
            log.info("获取service注入的request：{}",this.getRequest());
            log.info("获取注入的request：{}",request);
            log.info("登录系统的IP地址：{}",this.getIp());
            log.info("结果集："+result);
            if(StringUtil.isNotEmpty(result)){
                jhApiResult = JSON.parseObject(result,JHApiResult.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jhApiResult;
    }

    @Override
    public JHApiResult getJokes(HttpServletRequest request, Integer page, Integer pageSize) {
        JHApiResult jhApiResult = null;
        String sort = request.getParameter("sort");
        Map<String,Object> map = new HashMap<>();
        map.put("key",URLEnum.JOKE_URL.getKey());
        map.put("sort",sort==null?"ASC":sort);
        map.put("time",DateUtil.currentSeconds());
        map.put("page",page==null?1:page);
        map.put("pagesize",pageSize==null?5:pageSize);
        try {
            String result = httpAPIService.doGet(URLEnum.JOKE_URL.getUrl(), map);
            log.info("查询结果："+result);
            if (StringUtil.isNotEmpty(result)){
                jhApiResult = JSON.parseObject(result,JHApiResult.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jhApiResult;
    }

    @Override
    public boolean saveJokes(List<JokeVo> jokeVoList) {
        return false;
    }


}
